<template>
  <CardModules title="设备列表">
    <div class="device-list" v-if="treeData.length > 0">
      <a-tree default-expand-all :tree-data="treeData" :fieldNames="{ title: 'bridgeName', key: 'deviceId', children: 'deviceVOList' }">
        <template #title="{ dataRef }">
          <template v-if="dataRef.bridgeId">
            {{ dataRef.bridgeName }}
          </template>
          <template v-else>
            <div class="device-node" @click="handleSelect(dataRef)">
              <img :src="imageList[dataRef.deviceType]" alt="" />
              <div class="device-name" :title="dataRef.deviceName">
                {{ dataRef.deviceName }}
              </div>
              <div>
                <CheckCircleFilled style="color: #0f0" v-if="dataRef.status === true" />
                <CloseCircleFilled style="color: red" v-else-if="dataRef.status === false" />
              </div>
            </div>
          </template>
        </template>
      </a-tree>
    </div>
  </CardModules>
</template>
<script setup>
  import { api } from '/@/api/plat/bridge.js';
  import { onMounted, ref } from 'vue';
  import CardModules from '/@/components/cardModules/index.vue';

  const treeData = ref([]);
  const emit = defineEmits(['select']);
  const imageList = {
    0: '/images/icon/radar.png',
    1: '/images/icon/camera.png',
    2: '/images/icon/water.png',
    3: '/images/icon/ais.png',
  };

  function getBridgeList() {
    api.queryDeviceList().then(({ data }) => {
      const list = data.map((m) => {
        m.deviceId = 'bridge_' + m.bridgeId;
        return m;
      });
      treeData.value = list;
    });
  }

  function handleSelect(row) {
    emit('select', row);
  }

  function changeStatus(row) {
    for (let item of treeData.value) {
      const index = item.deviceVOList.findIndex((m) => m.secret === row.secret);
      if (index >= 0) {
        item.deviceVOList[index].status = row.status;
      }
    }
  }

  defineExpose({ changeStatus });

  onMounted(getBridgeList);
</script>

<style lang="less" scoped>
  @import './index.less';
</style>
